package com.inspectortime.webapp.inspector.scheduleRule;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.inspectortime.domain.Inspector;
import com.inspectortime.domain.ScheduleRule;
import com.inspectortime.repository.Repository;

/**
 * Performs two functions - Displays an "Are you sure?" page and deletes the selected schedule rule
 * 
 * @author bones
 *
 */
public class DeleteScheduleRuleController extends AbstractController {
	
	private static Log log = LogFactory.getLog(DeleteScheduleRuleController.class);
	
	private Repository repository;
	private String confirmView;
	private String successView;


	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		ModelAndView mv = null;
		ScheduleRule scheduleRule = null;
		
		String scheduleRuleId = request.getParameter("ruleId");
		String inspectorId = request.getParameter("inspectorId"); 
		String confirmParam = request.getParameter("confirm");
		
		Inspector inspector = repository.loadInspector(inspectorId);
		scheduleRule = inspector.getScheduleRuleById(scheduleRuleId);

		//This shouldn't ever happen
		if (scheduleRule == null) {
			throw new Exception("Tried to retrieve a non-existent scheduleRule for deletion.\nRuleId: " + scheduleRuleId +
								"\nInspectorId: " + inspectorId);
		}
		
		//Send user to confirm page
		if (StringUtils.isBlank(confirmParam)) {
			mv = new ModelAndView(this.confirmView);
		} else {
			
			inspector.getScheduleRules().remove(scheduleRule);
			inspector.save();
			
			mv = new ModelAndView(this.successView);
		}

		mv.addObject("inspector", inspector);
		mv.addObject("scheduleRule", scheduleRule);
		return mv;
	}
	
	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	public void setConfirmView(String confirmView) {
		this.confirmView = confirmView;
	}

	public void setSuccessView(String successView) {
		this.successView = successView;
	}
	



	
}
